<?php

namespace App\VO\ConvertibleCard;

use App\BO\ConvertibleCard\Constant as ConvertibleCardConstant;
use App\BO\ConvertibleCard\Helper as ConvertibleCardHelper;
use App\BO\User\UserBO;
use App\Entities\ConvertibleCardEntity;

trait CommonTrait
{
    private function assign(ConvertibleCardEntity $cardEntity)
    {
        $userId = UserBO::getUserId();
        $this->id = $cardEntity->getId();
        $this->title = $cardEntity->getTitle();
        $this->price = $this->priceConvert($cardEntity);
        $this->bannerImage = $cardEntity->getBanner();
        $this->canUserPurchaseCard = $this->canUserPurchaseCard($userId, $cardEntity);
        $this->purchaseLimit = $cardEntity->getPurchaseLimit();
    }

    private function typeName(ConvertibleCardEntity $cardEntity)
    {
        $type = $cardEntity->getType();
        return ConvertibleCardConstant::TYPE_NAMES[$type] ?? '';
    }

    private function statusName(ConvertibleCardEntity $cardEntity)
    {
        $status = ConvertibleCardHelper::calculateStatus($cardEntity);
        return ConvertibleCardConstant::STATUS_NAMES[$status] ?? '';
    }

    private function durationName(ConvertibleCardEntity $cardEntity)
    {
        $duration = $cardEntity->getDuration();
        if ($duration > 0) {
            return $duration . '天';
        }
        return '无限期';
    }

    private function priceConvert(ConvertibleCardEntity $cardEntity)
    {
        $price = $cardEntity->getPrice();
        return ConvertibleCardHelper::fen2yuan($price);
    }

    private function canUserPurchaseCard(int $userId, ConvertibleCardEntity $cardEntity)
    {
        $count = ConvertibleCardHelper::getUserAvailableCardCount($cardEntity, $userId);
        if ($cardEntity->getPurchaseLimit() == 0 || $count < $cardEntity->getPurchaseLimit()) {
            return true;
        }
        return false;
    }
}
